const express = require('express');
const fs = require('fs');
const path = require('path');

const userRouter = express.Router();

// 加载初始用户数据
let users = JSON.parse(fs.readFileSync(path.join(__dirname, '../data/users.json'), 'utf-8'));

// 获取用户列表
userRouter.get('/list', (req, res) => {
	res.json(users);
});

// 获取用户详情
userRouter.get('/detail/id', (req, res) => {
	const id = parseInt(req.params.id);
	const user = users.find(u => u.id === id);
	if (user) {
		res.json(user);
	} else {
		res.status(404).send('User not found');
	}
});

// 添加用户
userRouter.post('/add', (req, res) => {
	console.log("req", req);
	// const newUser = req.bady;
	// const newUser = req.params;
	const newUser = req.query;
	newUser.id = users.length + 1; // 简单地用数组长度+1作为新ID，实际项目中可能需要更复杂的逻辑来生成唯一ID
	users.push(newUser);
	fs.writeFileSync(path.join(__dirname, '../data/users.json'), JSON.stringify(users, null, 2));
	res.status(201).json(newUser);
});

// 更新用户
userRouter.put('/update/id', (req, res) => {
	const id = parseInt(req.params.id);
	const updateUser = req.body;
	const index = users.findIndex(u => u.id === id);
	if (index !== -1) {
		users[index] = { ...users[index], ...updateUser }; // 合并现有对象和更新对象
		fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(users, null, 2));
		res.json(users[index]);
	} else {
		res.status(404).send('User not found');
	}
});

// 删除用户
userRouter.delete('/delete/:id', (req, res) => {
	const id = parseInt(req.params.id);
	const index = users.findIndex(u => u.id === id);
	if (index !== -1) {
		const deleteUser = users.splice(index, 1)[0];
		fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(users, null, 2));
		res.json(deleteUser);
	} else {
		res.status(404).send('User not found');
	}
});

module.exports = userRouter;